import { parse } from '@vue/compiler-sfc';
import { create, all } from 'mathjs'
const config = {
    epsilon: 1e-12,
    matrix: 'Matrix',
    number: 'BigNumber', // 可选值：number BigNumber
    precision: 64,
    predictable: false,
    randomSeed: null
}
const math = create(all, config)
//判断公式中是否包含加减或乘除运算符且不同同时存在。
function isAddSubAndMulDivExclusive(formula) {
    // 使用字符串方法判断公式中是否包含加减运算符
    var hasAddSub = formula.includes('+') || formula.includes('-');

    // 使用字符串方法判断公式中是否包含乘除运算符
    var hasMulDiv = formula.includes('*') || formula.includes('/');

    // 判断加减和乘除运算符是否同时存在
    if (hasAddSub && hasMulDiv) {
        return false;
    } else {
        return true;
    }
}
//从公式中取出所有的参数数值。
function extractNumbersFromFormula(formula) {
    // 使用正则表达式匹配公式中的数值
    var regex = /\d+(\.\d+)?/g;
    var matches = formula.match(regex);
    // 返回匹配到的数值数组
    return matches;
}

//解析公式中的中间公式生成最简单的公式且支持小括号嵌套
//例如：1+2*3=1+6,(1+2)*3=3*3，(2*(3+1))-1=8-1
function simplifyFormula(formula, flag, flag1) {

    // 使用正则表达式匹配公式中的括号表达式

    var matches = formula.match(/\([^()]+\)/g);

    // 遍历所有括号表达式，递归调用simplifyFormula()函数计算结果并替换公式中的括号表达式
    if (matches != null && !flag1) {
        let flag1 = false;
        matches.forEach(function (match) {
            var result = simplifyFormula(match.slice(1, -1), true);
            if (match.startsWith("(") && match.substring(match.length - 1) == ')') {
                formula = formula.replace(match, "(" + result.toString() + ")");
                flag1 = true;
            } else {
                formula = formula.replace(match, result.toString());
            }
        });
        formula = simplifyFormula(formula, flag, flag1);
    }
    if (!flag && isAddSubAndMulDivExclusive(formula)) return formula;
    // 使用正则表达式匹配公式中的乘除表达式
    matches = formula.match(/[0-9.]+[\/*][0-9.]+/g);

    // 遍历所有乘除表达式，计算结果并替换公式中的乘除表达式
    if (matches != null) {
        matches.forEach(function (match) {
            var result = getExpressValue(match);
            formula = formula.replace(match, result.toString());
        });
        formula = simplifyFormula(formula, flag);
    }
    if (!flag) return formula;
    // 使用正则表达式匹配公式中的加减表达式
    matches = formula.match(/[0-9.-]+[\+\-][0-9.]+/g);

    // 遍历所有加减表达式，计算结果并替换公式中的加减表达式
    if (matches != null) {
        matches.forEach(function (match) {
            var result = getExpressValue(match);
            result = transferToNumber(result);
            formula = formula.replace(match, result.toString());
        });
        formula = simplifyFormula(formula, flag);

    }
    return formula;
}

function getModeValue(params, modeId) {
    let minLength;
    if (modeId == 1) {
        for (let i in params) {
            let param = params[i];
            let paramLength = getDecimalLength(param);
            if (!minLength) {
                minLength = paramLength
            } else if (paramLength < minLength) {
                minLength = paramLength;
            }
        }
    } else {
        for (let i in params) {
            let param = params[i];
            let paramLength = getSignificantDigitsLength(param);
            if (!minLength) {
                minLength = paramLength
            } else if (paramLength < minLength) {
                minLength = paramLength;
            }
        }
    }
    return { xyId: 0, ruleTypeId: modeId, ruleValue: minLength };
}
//获取跟随参数的公式结果值
function getFollowParamResult(formula) {
    let simpleFormula = simplifyFormula(formula);
    let params = extractNumbersFromFormula(simpleFormula);
    let modeId;
    var hasAddSub = simpleFormula.includes('+') || simpleFormula.includes('-');
    if (hasAddSub) {
        modeId = 1;
    }
    // 使用字符串方法判断公式中是否包含乘除运算符
    var hasMulDiv = simpleFormula.includes('*') || simpleFormula.includes('/');
    if (hasMulDiv) {
        modeId = 2;
    }
    return getModeValue(params, modeId);
}
//获取指定数值的有效数字的长度
export function getSignificantDigitsLength(number) {
    // 将数字转换为字符串
    const numberString = number.toString();

    // 移除符号和小数点
    let strippedString = numberString.replace(/[-+]?(\d*\.?\d+([eE][-+]?\d+)?)/, '$1');

    if (strippedString.indexOf("E") > 0) {
        strippedString = strippedString.substring(0, strippedString.indexOf("E"));
    }
    if (strippedString.indexOf("e") > 0) {
        strippedString = strippedString.substring(0, strippedString.indexOf("e"));
    }
    strippedString = strippedString.replace(/[+\-*/]/g, "")
    // 计算有效数字的长度
    // const significantDigitsLength = strippedString.replace(/^0+/, '').replace(/\.+$/, '').length;
    const significantDigitsLength = strippedString.replace(".", "").replace(/^0+/, "").length

    return significantDigitsLength;
}
//获取指定数值的小数位数的长度
export function getDecimalLength(inputString) {
    inputString = inputString.toString();
    // 使用正则表达式匹配小数部分
    const decimalMatch = inputString.match(/\.\d+/);

    // 如果没有匹配到小数部分，返回0
    if (!decimalMatch) {
        return 0;
    }

    // 获取匹配到的小数部分字符串
    const decimalPart = decimalMatch[0];

    // 返回小数部分字符串的长度（减去小数点的1）
    return decimalPart.length - 1;
}

//查询第1个既不是数字也不是小数点的字符用于提取包含单位的数据并分开
export function splitValueAndUnit(valueUnit) {
    let splitIndex = -1;
    for (let i = 0; i < valueUnit.length; i++) {
        const char = valueUnit.charAt(i);
        if (!/[\d.]/.test(char)) {
            splitIndex = i;
            break;
        }
    }
    if (splitIndex != -1) {
        let value = valueUnit.substring(0, splitIndex);
        let unitName = valueUnit.substring(splitIndex);
        return [value, unitName];
    }
    return ''; // 如果字符串中都是数字和小数点，返回null
}

//将科学技术法转为数值，例如：1.7e-3
function transferToNumber(inputNumber) {
    if (isNaN(inputNumber) || (typeof inputNumber == 'string' && inputNumber == '')) {
        return inputNumber
    }
    inputNumber = '' + inputNumber
    if (inputNumber.indexOf('e') <= 0 && inputNumber.indexOf('E') <= 0) {
        return inputNumber;
    }
    inputNumber = parseFloat(inputNumber)
    let eformat = inputNumber.toExponential() // 转换为标准的科学计数法形式（字符串）
    let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/) // 分离出小数值和指数值
    let number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]));
    return number;
}
//按小数点四舍六入五成双  symbol选项有：'=','<','<='
export function roundHalfEvenByPoint(num, scale, symbol) {
    if (!isNumber(num)) return;
    num = num.toString();
    var index = num.indexOf(".");
    var pointAfter = num.substring(index + 1);
    if (index == -1) {//说明为整数
        if (scale == 0) return num;
        if (!symbol || symbol == '==') {
            num += ".";
            for (var i = 0; i < scale; i++) {
                num += "0";
            }
            return num;
        }
    }
    const orgPointCount = getDecimalLength(num);
    if (symbol && symbol != '==') {
        if (scale >= orgPointCount) {
            return num;
        }
    }
    //例如原数据14.00 要求保留小数点 <=1 ，则结果应该是14.0
    if (orgPointCount > scale) {
        symbol = "==";
    }
    num = parseFloat(num);
    var d = scale || 0;
    var m = Math.pow(10, d);
    //避免舍入误差
    var n = +(d ? num * m : num).toFixed(8);
    var i = Math.floor(n),
        f = n - i;
    //考虑f中的舍入误差
    var e = 1e-8;
    var k = (i % 2 === 0) ? i : i + 1;
    var r =
        f > 0.5 - e && f < 0.5 + e ?
            k : Math.round(n);
    var result = d ? r / m : r;

    if (!symbol || symbol == '==') {
        result = result.toString();

        // 补零，如果修约位数不够
        const parts = result.split('.');
        if (scale > 0) {

            if (parts.length === 1)
                return result + '.' + '0'.repeat(scale);
            if (parts[1].length == scale) {
                return result;
            }
            return result + '0'.repeat(scale - parts[1].length);

        }
    }
    return result;

}
//按有效数字修约 symbol选项有：'==','<','<='
export function roundHalfEvenByYxsz(num, scale, symbol) {
    if (!symbol) symbol = "==";
    if (symbol == '<') {
        scale--;
    }
    // num = Math.abs(num);//相对偏差可能是负数
    num = transferToNumber(num);
    var fsLength;
    if (num > 0 && num < 0.001) {
        //科学计数法用负数表示,长春填写
        num += "";//转换成字符串
        var numArray = num.split("");
        num = "";
        var tt = 0;
        for (var t = 0; t < numArray.length; t++) {
            if (numArray[t] == '0' && tt == 0) {
                fsLength++;
                continue;
            }
            else if (numArray[t] == '.') {
                fsLength = 0;
                continue;
            }
            if (tt == 1) num += ".";
            num += numArray[t];
            tt++;
        }
    }

    num = num.toString();//转换成字符串
    var length = num.length;//字符串的长度
    var indexPoint = num.indexOf(".");
    if (indexPoint != -1) length--;//如果是小数，则位数减1。
    else {
        indexPoint = length;
        if (scale == length) return num;
    }
    var yxsz = 0;
    if (scale < indexPoint) {//如果指定的有效数字小于整数位数，则用科学计数法表示
        num = num.substring(0, 1) + "." + num.substring(1, indexPoint);
        yxsz = scale - 1;
    } else {
        yxsz = parseXfdNum(num, scale);
    }

    var result = roundHalfEvenByPoint(num, yxsz, symbol);
    if (fsLength) {
        result += "E-" + (fsLength + 1);
    } else if (num != result && scale < indexPoint) {
        if (indexPoint - 1 >= 1)
            result += "E+" + (indexPoint - 1);
    }
    return result;
}

export function isNumber(num) {
    var regex = /^[-+]?(\d+(\.\d*)?|\.\d+)(e[-+]?\d+)?$/i;
    return regex.test(num);
}

export function isCheckLimitValue(num){
    if (num == '/') return false;
    if (isNumber(num)) return false;
    if (num.indexOf("<") != -1 || num.indexOf("＜") != -1 || num.indexOf("ND") != -1 || num.indexOf("L") != -1 || num.indexOf("未检出") != -1) {
        return true;
    }
    return false;
}

export function getRealValue($resultComponent, num) {
    if (num == '/') return -3000;
    if (isNumber(num)) return num;
    if (num.indexOf("<") != -1 || num.indexOf("＜") != -1 || num.indexOf("ND") != -1 || num.indexOf("L") != -1 || num.indexOf("未检出") != -1) {
        let isResult = $resultComponent.attr("isResult");
        if (!isResult) {
            if ($resultComponent.hasClass("resultValue")) {
                isResult = 1;
                const checkLimitData = getCheckLimitDataByTr($resultComponent);
                if (!checkLimitData) {
                    isResult = 1;
                } else {
                    const checkLimitValue = checkLimitData.checkLimitValue;
                    if (checkLimitData.checkLimitTableId.startsWith("+")) {
                        num = checkLimitValue + checkLimitData.checkLimitTableId.substring(1)
                    } else {
                        const index = checkLimitData.checkLimitTableId.indexOf("+");
                        if (index > 0) {
                            return checkLimitData.checkLimitTableId.substring(0, index) + checkLimitValue;
                        }
                        num = checkLimitData.checkLimitTableId;
                    }
                    isResult = 2;
                    $resultComponent.data("resultValue", num);

                }
            } else {
                return 0;
            }
        }
        if (isResult == 1) {
            return -1000;
        } else if (isResult == 2) {
            return -1100;
        }
        return 0;
    }
    return -2000;
}

// Math字符检索公式替换
export function replaceMathFunciton(express) {
    let mathArray = ['abs', 'sqrt', 'random', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'log10', 'exp', 'pow', 'max', 'min', 'round', 'ceil', 'floor', 'last'];
    for (let i = 0; i < mathArray.length; i++) {
        const mathFunc = mathArray[i];
        const regex = new RegExp(`\\b${mathFunc}\\b`, 'g');
        if (mathFunc == 'last') {
            const lasts = express.match(/(?<=last\()(.+?)(?=\))/g);
            if (lasts && lasts.length > 0) {
                let lastValue;
                lasts.forEach(values => {
                    values.split(",").forEach(value => {
                        if (value.match(/[-+]?(\d*\.?\d+([eE][-+]?\d+)?)/)) {
                            lastValue = value;
                        }
                    })
                    if (!lastValue) {
                        throw new Error("未从" + express + "中匹配到最后个数字！");
                    }
                    express = express.replace("last(" + values + ")", lastValue);
                })
                continue;
            }
        }
        express = express.replace(regex, `Math.${mathFunc}`);
    }
    return express.replace("=", "==");
}
/**
 * 计算表达式的结果及使用公式信息修约
 * @param {公式信息} formula 
 * @param {表达式} express 
 */
export function getFormulaResult($result, formula, express) {
    let resultValue = getRuleAndExpressResult($result, formula, express);
    return resultValue;
}

function authoParsePow(num) {
    num = parseFloat(num);
    var fsLength;
    if (num > 0 && num < 0.001) {
        //科学计数法用负数表示,长春填写
        num += "";//转换成字符串
        var numArray = num.split("");
        num = "";
        var tt = 0;
        for (var t = 0; t < numArray.length; t++) {
            if (numArray[t] == '0' && tt == 0) {
                fsLength++;
                continue;
            }
            else if (numArray[t] == '.') {
                fsLength = 0;
                continue;
            }
            if (tt == 1) num += ".";
            num += numArray[t];
            tt++;
        }
        return { resultValue: num, fsLength: fsLength }
    }
    return;
}

/**
 * 获取指定检测类别的检出限值
 * @param {当前行对象} $tr 
 * @returns 
 */
export function getCheckLimitValueByTr($result) {
    const checkLimitData = getCheckLimitDataByTr($result);
    if (checkLimitData) {
        return checkLimitData.checkLimitValue;
    }
    return;
}

/**
 * 获取检出限数据
 * @param {当前行对象} $tr 
 * @returns 
 */
export function getCheckLimitDataByTr($result) {
    const $tr = $result.parents("tr:first");
    let checkDataList = $tr.data("checkData");
    if (!checkDataList) return;
    const jcxmId = $result.data("jcxm_id");
    if (!jcxmId && checkDataList.length > 1) {
        throw new Error("查询到多个检出限！");
    }
    if (jcxmId) {
        checkDataList = checkDataList.filter(item => {
            return item.jcxmId == jcxmId;
        })
        if (checkDataList.length == 0) {
            throw new Error("查询到指定检测项目的检出限！");
        }
    }
    if (checkDataList.length == 1) {
        return checkDataList[0];
    }
    throw new Error("查询到多个检出限！");
}


/**
 * 
 * @param {表达式} express 
 * @param {修约规则 0：四舍五入 1：四舍六入五成双} ruleId(xyId)
 * @param {修约方式 1：保留小数点 2：保留有效数字} modeId(ruleTypeId) 
 * @param {修约位数} digitCount (ruleValue)
 * @param {修约符号 <、<=、==、6(跟随检出限)、7(与参数保持一致)、8(跟随参数)} symbol(ruleConditionId)
 * @param isResult 是否是结果公式 0 是 1否
 * @returns 
 */
export function getRuleResult($result, resultValue, xyId, ruleTypeId, ruleValue, ruleConditionId, isResult) {
    if (isNaN(resultValue) || (typeof resultValue == 'string' && resultValue == '')) return '';
    if (!isNumber(xyId) || !isNumber(ruleTypeId) || (!isNumber(ruleValue) && ruleConditionId != 6)) return '';
    if (ruleConditionId == 6) {//跟随检出限
        let checkLimitValue = getCheckLimitValueByTr($result);
        if (!checkLimitValue) {
            throw new Error("当前公式的修约规则为跟随检出限，但未查询检出限值");
            // return { "resultValue": resultValue };
        }
        if (ruleTypeId == 1) {
            ruleValue = getDecimalLength(checkLimitValue);
        } else if (ruleTypeId == 2) {
            ruleValue = getSignificantDigitsLength(checkLimitValue);
        }
        ruleConditionId = "==";
    }
    let powValue;
    if (isResult == 0) {
        powValue = authoParsePow(resultValue);
        if (powValue) {
            resultValue = powValue.resultValue;
        }
    }
    let prefix = "";
    if (resultValue.toString().startsWith("-")) {
        prefix = "-";
        resultValue = parseFloat(resultValue.toString().substring(1));
    }
    if (xyId == 0) {
        if (ruleTypeId == 2) {
            let orgResultValue = resultValue;
            let resultValueStr = resultValue.toString();
            let resultLength = resultValueStr.length;
            let indexPoint = resultValueStr.indexOf(".");
            if (resultValueStr.substring(0, 1) == '-') {
                indexPoint--;
            }
            if (indexPoint == -1) {
                indexPoint = resultLength;
                if (ruleValue == resultLength) {
                    if (powValue) {
                        resultValue += "E-" + (powValue.fsLength + 1);
                    }
                    return prefix + resultValue;
                }
            }
            if (ruleValue < indexPoint) {//如果指定的有效数字小于整数位数，则用科学计数法表示
                if (resultValueStr.substring(0, 1) != '-') {
                    resultValueStr = resultValueStr.substring(0, 1) + "." + resultValueStr.substring(1, indexPoint);
                } else {
                    resultValueStr = resultValueStr.substring(0, 1) + resultValueStr.substring(1, 2) + "." + resultValueStr.substring(2, indexPoint);
                }
                ruleValue = ruleValue - 1;
                resultValue = parseFloat(resultValueStr);
            } else {
                ruleValue = parseXfdNum(resultValue, ruleValue);
            }
            resultValue = roundAndPadWithZeros(resultValue, ruleValue, "==");
            if (powValue) {
                resultValue += "E-" + (powValue.fsLength + 1);
            } else if (orgResultValue != resultValue && ruleValue < indexPoint && indexPoint - 1 >= 1) {
                resultValue += "E+" + (indexPoint - 1);
            }
            return prefix + resultValue;
        } else {
            resultValue = roundAndPadWithZeros(resultValue, ruleValue, "==");
        }
    } else if (xyId == 1) {
        if (ruleTypeId == 1) {
            resultValue = roundHalfEvenByPoint(resultValue, ruleValue, ruleConditionId);
        } else {
            let orgResultValue = resultValue;
            let resultValueStr = resultValue.toString();
            let resultLength = resultValueStr.length;
            let indexPoint = resultValueStr.indexOf(".");
            if (indexPoint == -1) {
                indexPoint = resultLength;
                if (ruleValue == resultLength) {
                    if (powValue) {
                        resultValue += "E-" + (powValue.fsLength + 1);
                    }
                    return resultValue;
                }
            }
            // if (ruleValue < indexPoint) {//如果指定的有效数字小于整数位数，则用科学计数法表示
            //     resultValueStr = resultValueStr.substring(0, 1) + "." + resultValueStr.substring(1, indexPoint);
            //     // ruleValue = ruleValue - 1;
            //     debugger;
            //     resultValue = parseFloat(resultValueStr);
            // }
            resultValue = roundHalfEvenByYxsz(resultValue, ruleValue, ruleConditionId);
            if (powValue) {
                resultValue += "E-" + (powValue.fsLength + 1);
            }
            // else if (orgResultValue != resultValue && ruleValue < indexPoint && indexPoint - 1 >= 1) {
            //     resultValue += "E+" + (indexPoint - 1);
            // }
            return prefix + resultValue;
        }
    }
    if (powValue) {
        resultValue += "E-" + (powValue.fsLength + 1);
    }
    return prefix + resultValue;
}



export function getRuleAndExpressResult($result, formula, express) {
    let resultValue = getExpressResult(express);
    if (formula.isResult == 0) {//最终公式
        resultValue = compareCheckLimtValue($result, resultValue, formula,express);
    } else if (formula.isResult == 1) {//中间公式
        // if (formula.followParam == 0) {//修约跟随参数
        //     formula = getFollowParamResult(express);
        // } else if (formula.isSame == 1) {//与参数修约一致 0否 1是
        //     //取任意参数值不用考虑多个参数的有数数字或小数点保留位数不一致的情况。
        //     const paramValue = formula.paramList[0].value;
        //     if (paramValue || typeof paramValue == 'number') {
        //         if (formula.modeId == 1) {
        //             formula.digitCount = getDecimalLength(paramValue);
        //         } else if (formula.modeId == 2) {
        //             formula.digitCount = getSignificantDigitsLength(paramValue);
        //         }
        //         formula.symbol = "==";
        //     }
        // }
        // resultValue = getRuleResult($result, resultValue, formula.ruleId, formula.modeId, formula.digitCount, formula.symbol, formula.isResult);
        resultValue = getCondtionExpressResult($result, formula, resultValue,express);

    }
    return resultValue;
}

/**
 * 根据公式的修约条件对结果值修约。
 * @param {公式数据} formula 
 * @param {公式结果值} resultValue 
 * @returns 
 */
export function getCondtionExpressResult($result, formula, resultValue,express) {
    //公式结果进行修约,根据结果值的范围进行修约，比如：结果值<1，小数点保留1位，结果值>=1,小数点保留2位
    let ruleList = formula.ruleList;
    if (!ruleList) return resultValue;
    for (let rule of ruleList) {
        if (rule.ruleConditionId == 8) {//跟随参数
            rule = getFollowParamResult(express);
        } else if (rule.ruleConditionId == 7 || rule.ruleConditionId1 == 7) {//与参数修约一致 0否 1是 
            //注：rule.ruleConditionId == '=='这个条件不能删掉因为第2次用到这个公式时ruleConditionId:"=="，因为后面8行赋值成“==”了。
            //取任意参数值不用考虑多个参数的有数数字或小数点保留位数不一致的情况。
            const paramValue = formula.paramList[0].value;
            if (paramValue || typeof paramValue == 'number') {
                if (rule.ruleTypeId == 1) {
                    rule.ruleValue = getDecimalLength(paramValue);
                } else if (rule.ruleTypeId == 2) {
                    rule.ruleValue = getSignificantDigitsLength(paramValue);
                }
                rule.ruleConditionId = "==";
                rule.ruleConditionId1 = 7;
            }
        } else if (!rule.ruleTypeId || (!rule.ruleValue && rule.ruleConditionId != 6)) {//6:跟随检测限，修约位数不用填。
            //ruleTypeId:保留小数点、有效数字 ruleValue：保留位数 ruleConditionId:6跟随检测限 8跟随参数
            throw new Error("修约规则不完整！");
        }
        //rule.conditionId:[>=,>,<,<=,==],rule.conditionValue:条件值 1，2，3..
        //例如：resultValue：0.8，则 0.8 < 1
        if (rule.conditionId && rule.conditionValue) {//结果值不符合此条件
            if (rule.conditionId == '=') {
                rule.conditionId = rule.conditionId.replace("=", "==");
            }
            try {
                if (!eval(resultValue + rule.conditionId + rule.conditionValue)) {
                    continue;
                }
            } catch (e) {
                throw new Error(resultValue + rule.conditionId + rule.conditionValue);
            }

        }
        if(!isNumber(rule.xyId)){
            rule.xyId = 1;
        }
        resultValue = getRuleResult($result, resultValue, rule.xyId, rule.ruleTypeId, rule.ruleValue, rule.ruleConditionId);
        if (typeof resultValue == 'object') {
            break;
        }
    }
    return resultValue;
}

function compareCheckLimtValue($result, resultValue, formula,express) {
    if (!isNumber(resultValue)){
        resultValue = getCondtionExpressResult($result, formula, resultValue,express);
        return resultValue;
    } 
    const checkLimitData = getCheckLimitDataByTr($result);
    if (!checkLimitData) {
        resultValue = getCondtionExpressResult($result, formula, resultValue,express);
        return resultValue;
    }
    const checkLimitValue = checkLimitData.checkLimitValue;
    //换算单位后的修约倍数
    let times = checkLimitData.times;
    if (times && times != 1) {
        times = parseFloat(times);
        if (times != 1) {
            resultValue = getExpressResult(resultValue + "*" + times);
            if (formula && formula.symbol && formula.symbol == 6) {
                resultValue = getRuleResult($result, resultValue, formula.ruleId, formula.modeId, formula.digitCount, formula.symbol, formula.isResult);
            } else {
                formula = { ruleId: 1, modeId: 1, symbol: 6 };
                resultValue = getRuleResult($result, resultValue, formula.ruleId, formula.modeId, formula.digitCount, formula.symbol, formula.isResult);
            }
        }
    }
    if (parseFloat(resultValue) < parseFloat(checkLimitValue) || resultValue < 0) {
        if (checkLimitData.checkLimitTableId.startsWith("+")) {
            return checkLimitValue + checkLimitData.checkLimitTableId.substring(1)
        } else {
            const index = checkLimitData.checkLimitTableId.indexOf("+");
            if (index > 0) {
                return checkLimitData.checkLimitTableId.substring(0, index) + checkLimitValue;
            }
            return checkLimitData.checkLimitTableId;
        }

    }
    if (!times || times == 1) {
        resultValue = getCondtionExpressResult($result, formula, resultValue,express);
    }
    return resultValue;
}
//计算表达式的结果值。
export function getExpressResult(express) {
    let resultValue;
    express = replaceMathFunciton(express);
    resultValue = getExpressValue(express);
    if (resultValue == '') return resultValue;
    return parseFloat(resultValue);
}
export function getExpressValue(express) {
    if (express.indexOf("--") != -1) {
        express = express.replace("--", "+");
    }
    let value;
    try {
        value = math.format(math.evaluate(express));
    } catch (e) {
        try {
            value = eval(express)
        } catch (e1) {
            value = '';
        }
    }
    //分母为0时value：Infinity或-Infinity
    if(typeof value == 'string' && value.indexOf("Infinity") != -1){
        return '';
    }
    if (isNaN(value)) return '';
    return value;
}
//验证指定的有效数字的小数位数
export function parseXfdNum(value, yxszNum) {
    var newValue = (parseFloat(value).toPrecision(yxszNum)) + '';
    if (newValue.indexOf(".") == -1) return 0;
    return newValue.substr(newValue.indexOf(".") + 1).length;
}

//保留指定位数的四舍五入函数
function roundAndPadWithZeros(number, decimalPlaces, symbol) {
    if (isNaN(number)) {
        return NaN; // 如果输入不是有效的数字，返回NaN
    }
    number = parseFloat(number);
    decimalPlaces = parseInt(decimalPlaces);
    if (symbol == '<') decimalPlaces--;
    const roundedNumber = Number(number.toFixed(decimalPlaces)); // 修约到指定的小数位数
    const roundedString = roundedNumber.toString();
    if (symbol != '==') return roundedString;
    // 检查小数部分的长度
    const decimalIndex = roundedString.indexOf('.');
    if (decimalIndex === -1) {
        if (decimalPlaces == 0) {
            return roundedString;
        }
        // 如果没有小数部分，补零
        return roundedString + "." + '0'.repeat(decimalPlaces);
    } else {
        // 如果有小数部分，补零直到达到指定的小数位数
        const currentDecimalPlaces = roundedString.length - decimalIndex - 1;
        if (currentDecimalPlaces < decimalPlaces) {
            const zerosToAdd = decimalPlaces - currentDecimalPlaces;
            return roundedString + '0'.repeat(zerosToAdd);
        } else {
            return roundedString;
        }
    }
}

export function isTrueCondtion(condition) {
    let condtionArray = condition.split("φ");
    if (condtionArray.length != 4 && condtionArray.length != 9) {
        alert("检出限条件不完整！");
        return;
    }
    let newCondtion = '';
    for (let i = 0; i < condtionArray.length; i++) {
        if (i == 3 || i == 8) continue;
        if (i == 4) {
            if (condtionArray[i] == '且') condtionArray[i] = "&&";
            else if (condtionArray[i] == '或') condtionArray[i] = "||";
        }
        newCondtion += condtionArray[i];
    }
    let result = getExpressResult(newCondtion);
    if (typeof (result) && result) return true;
    return false;
}

export function setLineRrule(value) {
    var valueArray = (value + '').split('');
    var pointIndex = (value + '').indexOf('.');
    var t = 1;
    var jiuNum = 0;//'9'的个数
    for (var i in valueArray) {
        if (i <= pointIndex) continue;
        if (t == 4) break;
        if (jiuNum == 4) break;
        if (jiuNum >= 1) {
            if (valueArray[i] == 9) jiuNum++;
            else break;
        }
        if (valueArray[i] == 9) jiuNum++;
        t++;
    }
    return value.toString().substring(0, parseInt(i) + 1);
}

//从字符串中提取数字
export function extractNumbersFromString(str) {
    // 使用正则表达式匹配字符串中的数字
    var regex = /[+-]?\d+(\.\d+)?/g;
    var matches = str.match(regex);

    // 返回匹配到的数字数组
    return matches;
}
